package com.poor.user.client.controller;

import com.alibaba.fastjson.JSON;
import com.poor.core.Result;
import com.poor.core.ResultGenerator;
import com.poor.user.client.model.request.UserRequestBean;
import com.poor.user.client.service.UserService;
import com.poor.utils.TimeUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/add")
    public Result register(@RequestBody UserRequestBean userRequestBean) {
        userService.registerUser(userRequestBean);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 微信小程序登录接口
     * ps:根据unionId查询,有则登录，没有则注册
     *
     * @param userRequestBean
     * @return
     */
    @PostMapping("/wx/login")
    public Result wxLogin(@RequestBody UserRequestBean userRequestBean) {
        List<UserRequestBean> userRequestBeanList = userService.findByWxUnionId(userRequestBean);
        if (userRequestBeanList.size() > 0) {
            ResultGenerator.setMessage("登录成功");
        } else {
            userService.registerUser(userRequestBean);
            ResultGenerator.setMessage("注册成功");
            userRequestBeanList = userService.findByWxUnionId(userRequestBean);
        }
        if(TimeUtils.DateToYMD(new Date()).equals(TimeUtils.DateToYMD(userRequestBeanList.get(0).getUserSignTime()))){
          userRequestBeanList.get(0).setUserIsSign(true);
        }else{
            userRequestBeanList.get(0).setUserIsSign(false);
        }
        return ResultGenerator.genSuccessResult(userRequestBeanList.get(0));
    }

    /**
     * 用户签到
     *
     * @param userRequestBean
     * @return
     */
    @PostMapping("/sign")
    public Result sign(@RequestBody UserRequestBean userRequestBean) {
        String signTime= TimeUtils.DateToYMD(new Date());//签到的时间
        if(signTime.equals(TimeUtils.DateToYMD(userRequestBean.getUserSignTime()))){
            return ResultGenerator.genFailResult("已签到,请明天再来");
        }else{
            Integer currentIntegral=userRequestBean.getUserIntegral()+5;
            userRequestBean.setUserIntegral(currentIntegral);
            userRequestBean.setUserSignTime(new Date());
            userService.updateUser(userRequestBean);
            ResultGenerator.setMessage("签到成功,积分+5");
            userRequestBean.setUserIsSign(true);
            return ResultGenerator.genSuccessResult(userRequestBean);
        }

    }
}
